<template>
  <view class="warehouse-container">
    <!-- 页面头部 -->
    <view class="page-header">
      <text class="page-title">炼轧计划编制</text>
    </view>

    <!-- 出库信息区域 -->
    <view class="info-section">
      <view class="section-header">
        <text class="section-title">计划信息</text>
      </view>

      <!-- 出库类型标签页 -->
      <view class="in-type-tabs">
        <view
          class="tab-item"
          :class="{ active: formData.outType === '三相' }"
          @click="switchOutType('三相')"
        >
          <text class="tab-text">三相</text>
        </view>
        <view
          class="tab-item"
          :class="{ active: formData.outType === '提纯' }"
          @click="switchOutType('提纯')"
        >
          <text class="tab-text">提纯</text>
        </view>
        <view
          class="tab-item"
          :class="{ active: formData.outType === '轧制' }"
          @click="switchOutType('轧制')"
        >
          <text class="tab-text">轧制</text>
        </view>
      </view>

      <view class="info-form">
        <view class="form-item">
          <text class="form-label required">创建日期</text>
          <picker
            class="form-picker"
            mode="date"
            :value="formData.currentDate"
            @change="handleDateChange"
          >
            <view class="picker-content">
              <text>{{ formData.currentDate }}</text>
              <text class="picker-arrow">></text>
            </view>
          </picker>
        </view>

        <view class="form-item">
          <text class="form-label">计划备注</text>
          <input
            class="form-input"
            v-model="formData.planRemark"
            placeholder="请输入计划备注"
          />
        </view>

        <!-- 领料工序（仅三相显示） -->
        <!-- <view class="form-item" v-if="formData.outType === '三相'">
          <text class="form-label">领料工序</text>
          <view class="process-display">{{ currentProcess.processName }}</view>
        </view> -->
      </view>
    </view>

    <!-- 查询/选择区 -->
    <view class="material-section">
      <view class="section-header">
        <text class="section-title">计划编制</text>
        <view class="time-filter-buttons">
          <button
            class="filter-btn"
            :class="{ active: timeFilter === 'today' }"
            @tap="
              handleTimeChange('today');
              searchContract();
            "
          >
            当日
          </button>
          <button
            class="filter-btn"
            :class="{ active: timeFilter === 'week' }"
            @tap="
              handleTimeChange('week');
              searchContract();
            "
          >
            本周
          </button>
          <button
            class="filter-btn"
            :class="{ active: timeFilter === 'month' }"
            @tap="
              handleTimeChange('month');
              searchContract();
            "
          >
            本月
          </button>
        </view>
      </view>
      <view class="purchase-search-area">
        <view class="scan-input-group">
          <view class="input-row">
            <input
              v-model="searchForm.materialName"
              class="material-input"
              placeholder="输入物料名称"
              @confirm="searchContract"
            />
            <input
              v-model="searchForm.customerName"
              class="material-input"
              placeholder="输入客户名称"
              @confirm="searchContract"
            />
            <button class="search-btn" @click="searchContract">搜索</button>
          </view>
        </view>
      </view>
      <view class="tab-header">
        <button
          class="tab-btn"
          :class="{ active: activeTab === 'current' }"
          @click="activeTab = 'current'"
        >
          合同内容 ({{ currentTable.length }})
        </button>
        <button
          class="tab-btn"
          :class="{ active: activeTab === 'selected' }"
          @click="activeTab = 'selected'"
        >
          计划编制 ({{ selectedTable.length }})
        </button>
      </view>
      <!-- 库存查询结果表格 -->
      <view class="material-table-section">
        <!-- 当前数据Tab -->
        <view v-if="activeTab === 'current'" class="tab-content">
          <view class="table-header">
            <text class="header-cell">创建日期</text>
            <text class="header-cell">合同编号</text>
            <text class="header-cell">产品大类</text>
            <text class="header-cell">标准</text>
            <text class="header-cell">钢种</text>
            <text class="header-cell">品名</text>
            <text class="header-cell">交货状态</text>
            <text class="header-cell">交货期</text>
            <text class="header-cell">物料名称</text>
            <text class="header-cell">规格</text>
            <text class="header-cell">合同重量(KG)</text>
            <text class="header-cell">合同数量(件)</text>

            <text class="header-cell">操作</text>
          </view>

          <view v-for="item in currentTable" :key="item.id" class="table-row">
            <text class="table-cell">{{
              dateHelperApi.formatDate(item.createTime)
            }}</text>
            <text class="table-cell">{{ item.contractNo }}</text>
            <text class="table-cell">
              {{ item.prod_class_name }}
            </text>
            <text class="table-cell">
              {{ item.standNo }}
            </text>
            <text class="table-cell">
              {{ item.steelGradeName }}
            </text>
            <text class="table-cell">
              {{ item.prodName }}
            </text>
            <text class="table-cell">
              {{ item.delivStatus }}
            </text>
            <text class="table-cell">
              {{ item.planDeliverDate }}
            </text>
            <text class="table-cell">
              {{ item.materialName }}
            </text>
            <text class="table-cell">
              {{ item.prodSpec }}
            </text>
            <text class="table-cell">
              {{ item.prodCount }}
            </text>
            <text class="table-cell">
              {{ item.transCount }}
            </text>
            <button class="add-btn" @tap="addToOutList(item)">添加</button>
          </view>
        </view>

        <!-- 待出库数据Tab -->
        <view v-if="activeTab === 'selected'" class="tab-content">
          <!-- 表单布局 - 始终显示 -->
          <view class="plan-form-container">
            <view class="form-section">
              <view class="form-row">
                <view class="form-group">
                  <text class="form-label required">计划日期</text>
                  <picker
                    class="form-picker"
                    mode="date"
                    :value="currentPlanItem.planDate || formData.currentDate"
                    @change="handlePlanDateChange"
                  >
                    <view class="picker-content">
                      <text>{{
                        currentPlanItem.planDate || formData.currentDate
                      }}</text>
                      <text class="picker-arrow">></text>
                    </view>
                  </picker>
                </view>
              </view>

              <view class="form-row">
                <view class="form-group">
                  <text class="form-label">标准</text>
                  <picker
                    class="form-picker"
                    mode="selector"
                    :range="standards"
                    :value="currentPlanItem.standIndex || 0"
                    @change="handleStandardChange"
                    :disabled="!standards.length"
                  >
                    <view class="picker-content">
                      <text>{{ currentPlanItem.standNo || "请选择标准" }}</text>
                      <text class="picker-arrow">></text>
                    </view>
                  </picker>
                </view>

                <view class="form-group">
                  <text class="form-label">钢种</text>
                  <picker
                    class="form-picker"
                    mode="selector"
                    :range="steelGrades"
                    :value="currentPlanItem.steelGradeIndex || 0"
                    @change="handleSteelGradeChange"
                    :disabled="!steelGrades.length"
                  >
                    <view class="picker-content">
                      <text>{{
                        currentPlanItem.steelGradeName || "请选择钢种"
                      }}</text>
                      <text class="picker-arrow">></text>
                    </view>
                  </picker>
                </view>
              </view>

              <view class="form-row">
                <view class="form-group">
                  <text class="form-label">规格</text>
                  <picker
                    class="form-picker"
                    mode="selector"
                    :range="specs"
                    :value="currentPlanItem.specIndex || 0"
                    @change="handleSpecChange"
                    :disabled="!specs.length"
                  >
                    <view class="picker-content">
                      <text>{{
                        currentPlanItem.prodSpec || "请选择规格"
                      }}</text>
                      <text class="picker-arrow">></text>
                    </view>
                  </picker>
                </view>
              </view>

              <view class="form-row">
                <view class="form-group">
                  <text class="form-label">计划重量(KG)</text>
                  <input
                    type="digit"
                    class="modern-input"
                    placeholder="请输入计划重量"
                    v-model.number="currentPlanItem.ProdCount"
                    @blur="validateNumber($event, currentPlanItem, 'ProdCount')"
                  />
                </view>

                <view class="form-group">
                  <text class="form-label">计划数量(炉/批/件)</text>
                  <input
                    type="number"
                    class="modern-input"
                    placeholder="请输入计划数量"
                    v-model.number="currentPlanItem.TransCount"
                    @blur="
                      validateNumber($event, currentPlanItem, 'TransCount')
                    "
                  />
                </view>
              </view>
              <view class="form-row button-row">
                <button class="btn-reset" @click="showResetConfirm">
                  重置
                </button>
                <button
                  class="btn-submit"
                  @click="submitCurrentPlan"
                  :disabled="!canSubmitCurrentPlan"
                >
                  创建
                </button>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
    <!--计划列表，创建成功后显示当前计划列表 -->
    <view class="material-section">
      <view class="section-header">
        <text class="section-title">计划列表</text>
      </view>

      <view class="tab-content">
        <view class="table-header">
          <view class="header-cell">计划日期</view>
          <view class="header-cell">标准</view>
          <view class="header-cell">钢种</view>
          <view class="header-cell">规格</view>
          <view class="header-cell">计划重量(KG)</view>
          <view class="header-cell">计划数量(炉/批/件)</view>
        </view>

        <view
          class="table-row"
          v-for="(item, index) in querySelectTable"
          :key="index"
        >
          <view class="table-cell">{{ item.planDate }}</view>
          <view class="table-cell">{{ item.standNo }}</view>
          <view class="table-cell">{{ item.steelGradeName }}</view>
          <view class="table-cell">{{ item.prodSpec }}</view>
          <view class="table-cell">{{ item.outProdCount }}</view>
          <view class="table-cell">{{ item.outTransCount }}</view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { dateHelperApi } from "@/pages/smart/utils/date-helper";

export default {
  data() {
    return {
      // 临时计划项（用于selectedTable为空时的编辑）
      _tempPlanItem: null,

      // 当前激活的标签页
      activeTab: "current",

      // 表单数据
      formData: {
        currentDate: dateHelperApi.getCurrentDate(),
        outType: "三相",
        warehouseCode: "",
        warehouseName: "",
      },

      // 当前仓库信息
      currentWarehouse: {
        warehouseCode: "",
        warehouseName: "请选择仓库",
      },

      // 当前工序信息
      currentProcess: {
        processName: "",
      },

      // 搜索表单
      searchForm: {
        materialCode: "",
        materialName: "",
        customerName: "",
      },

      // 时间筛选器
      timeFilter: "today",

      // 库存表格数据
      currentTable: [],

      // 待出库表格数据
      selectedTable: [],

      // 选中行
      selectedRows: [],

      // 加载状态
      loading: false,

      // 表单重构新增数据
      // 当前计划索引
      currentPlanIndex: 0,

      // 数据源（预留）
      standards: [], // 标准列表
      steelGrades: [], // 钢种列表
      specs: [], // 规格列表
    };
  },

  computed: {
    // 日期工具命名空间（供模板使用）
    dateHelperApi() {
      return dateHelperApi;
    },

    // 是否可以提交
    canSubmit() {
      return this.selectedTable.length > 0;
    },

    // 总数量
    totalCount() {
      return this.selectedTable.reduce(
        (sum, item) => sum + (Number(item.outTransCount) || 0),
        0
      );
    },

    // 总重量
    totalWeight() {
      return this.selectedTable.reduce(
        (sum, item) => sum + (Number(item.outProdCount) || 0),
        0
      );
    },

    // 当前计划项
    currentPlanItem() {
      // 如果selectedTable中有数据，返回对应项
      if (
        this.selectedTable.length > 0 &&
        this.selectedTable[this.currentPlanIndex]
      ) {
        return this.selectedTable[this.currentPlanIndex];
      }

      // 如果selectedTable为空，返回临时对象用于编辑
      // 使用Vue的响应式数据存储临时对象
      if (!this._tempPlanItem) {
        this._tempPlanItem = {
          planDate: this.formData.currentDate,
          standNo: "",
          steelGradeName: "",
          prodSpec: "",
          ProdCount: 0,
          TransCount: 0,
          standIndex: -1,
          steelGradeIndex: -1,
          specIndex: -1,
          showError: false,
        };
      }
      return this._tempPlanItem;
    },

    // 是否可以提交当前计划
    canSubmitCurrentPlan() {
      const item = this.currentPlanItem;
      return item && item.ProdCount !== null && item.ProdCount !== undefined && item.ProdCount !== '' && 
             item.TransCount !== null && item.TransCount !== undefined && item.TransCount !== '';
    },
  },

  onLoad() {
    this.initData();
  },

  onBackPress() {
    if (this.selectedTable.length > 0) {
      uni.showModal({
        title: "提示",
        content: "有待出库数据，确认不操作出库吗？",
        success: (res) => {
          if (res.confirm) {
            uni.navigateBack();
          }
        },
      });
      return true;
    }
  },

  methods: {
    // 初始化数据
    async initData() {
      try {
        // 获取当前仓库信息
        // this.loadCurrentWarehouse();
        // // 获取目标仓库选项（提纯用）
        // await this.loadTargetWarehouses();

        // 加载数据源
        await this.loadDataSources();
      } catch (error) {
        console.error("初始化数据失败:", error);
        uni.showToast({
          title: "初始化失败",
          icon: "error",
        });
      }
    },

    // // 加载当前计划类型信息
    // loadCurrentWarehouse() {
    //   const userConfig = this.$store.state.user.userConfig;
    //   if (userConfig && userConfig.wmName) {
    //     this.currentWarehouse = {
    //       warehouseCode: userConfig.wmCode || "DEFAULT",
    //       warehouseName: userConfig.wmName,
    //     };
    //     this.formData.warehouseCode = this.currentWarehouse.warehouseCode;
    //     this.formData.warehouseName = this.currentWarehouse.warehouseName;
    //   }
    // },

    // 加载目标仓库选项
    // async loadTargetWarehouses() {
    //   try {
    //     // 获取第1页，每页100条数据，筛选原料仓库
    //     const params = {
    //       pageNo: 1,
    //       pageSize: 100,
    //       dictType: "wm_name_po",
    //     };
    //     const response = await warehouseApi.getWarehouseList(params);
    //     if (response.code === 0) {
    //       // 将数据转换为下拉选项格式，根据API返回的字段名称
    //       this.targetWarehouseOptions = (response.data.list || []).map(
    //         (item) => ({
    //           value: item.value,
    //           text: item.label,
    //           warehouseName: item.label, // 用于显示
    //         })
    //       );
    //       console.log("目标仓库数据加载成功:", this.targetWarehouseOptions);
    //     }
    //   } catch (error) {
    //     console.error("加载目标仓库失败:", error);
    //   }
    // },

    // 切换出库类型
    switchOutType(type) {
      this.formData.outType = type;
      this.resetSearch();
      this.selectedRows = [];
      this.selectedTable = [];
    },

    // 选择行
    selectRow(index) {
      const rowIndex = this.selectedRows.indexOf(index);
      if (rowIndex > -1) {
        this.selectedRows.splice(rowIndex, 1);
      } else {
        this.selectedRows.push(index);
      }
    },

    // 处理日期变更
    handleDateChange(e) {
      this.formData.currentDate = e.detail.value;
    },

    /* 时间选择处理 */
    handleTimeChange(timeFilter) {
      this.timeFilter = timeFilter;

      // 使用通用的updateDateRange函数
      const result = dateHelperApi.updateDateRange(timeFilter, {
        callback: ({ startDate, endDate }) => {
          // 更新时间范围
          this.timeRange = {
            startTime: startDate,
            endTime: endDate,
          };
        },
      });
    },

    // 处理计划日期变更
    handlePlanDateChange(e) {
      if (this.currentPlanItem) {
        this.$set(this.currentPlanItem, "planDate", e.detail.value);
      }
    },

    // 处理标准选择
    handleStandardChange(e) {
      if (this.currentPlanItem && this.standards.length > 0) {
        const selectedIndex = e.detail.value;
        this.$set(this.currentPlanItem, "standIndex", selectedIndex);
        this.$set(
          this.currentPlanItem,
          "standNo",
          this.standards[selectedIndex]
        );
      }
    },

    // 处理钢种选择
    handleSteelGradeChange(e) {
      if (this.currentPlanItem && this.steelGrades.length > 0) {
        const selectedIndex = e.detail.value;
        this.$set(this.currentPlanItem, "steelGradeIndex", selectedIndex);
        this.$set(
          this.currentPlanItem,
          "steelGradeName",
          this.steelGrades[selectedIndex]
        );
      }
    },

    // 处理规格选择
    handleSpecChange(e) {
      if (this.currentPlanItem && this.specs.length > 0) {
        const selectedIndex = e.detail.value;
        this.$set(this.currentPlanItem, "specIndex", selectedIndex);
        this.$set(this.currentPlanItem, "prodSpec", this.specs[selectedIndex]);
      }
    },

    // 提交当前计划
    submitCurrentPlan() {
      // 先同步数据到selectedTable
      if (!this.syncCurrentPlanToTable()) {
        return;
      }

      const item = this.currentPlanItem;

      // 验证必填项
      if (!item.planDate) {
        uni.showToast({
          title: "请选择计划日期",
          icon: "none",
        });
        return;
      }

      if (item.ProdCount === null || item.ProdCount === undefined || item.ProdCount === '' ||
          item.TransCount === null || item.TransCount === undefined || item.TransCount === '') {
        uni.showToast({
          title: "请填写完整的计划量",
          icon: "none",
        });
        return;
      }

      // 验证数字有效性
      if (isNaN(Number(item.ProdCount)) || isNaN(Number(item.TransCount))) {
        uni.showToast({
          title: "计划量格式错误",
          icon: "none",
        });
        return;
      }

      // 调用原有的提交方法
      this.submitOutOrder();
    },

    // 重置当前计划
    resetCurrentPlan() {
      const item = this.currentPlanItem;
      if (item) {
        this.$set(item, "planDate", this.formData.currentDate);
        this.$set(item, "standNo", "");
        this.$set(item, "steelGradeName", "");
        this.$set(item, "prodSpec", "");
        this.$set(item, "ProdCount", 0);
        this.$set(item, "TransCount", 0);
        this.$set(item, "standIndex", -1);
        this.$set(item, "steelGradeIndex", -1);
        this.$set(item, "specIndex", -1);
      }
    },

    // 导航计划
    navigatePlan(direction) {
      const newIndex = this.currentPlanIndex + direction;
      if (newIndex >= 0 && newIndex < this.selectedTable.length) {
        this.currentPlanIndex = newIndex;
      }
    },

    // 加载标准数据（预留方法）
    async loadStandards() {
      // TODO: 调用API获取标准数据
      // this.standards = await api.getStandards();
      // 临时模拟数据用于测试
      this.standards = ["GB/T 700", "GB/T 1591", "GB/T 3077", "GB/T 4171"];
    },

    // 加载钢种数据（预留方法）
    async loadSteelGrades() {
      // TODO: 调用API获取钢种数据
      // this.steelGrades = await api.getSteelGrades();
      // 临时模拟数据用于测试
      this.steelGrades = ["Q235", "Q345", "Q390", "Q420", "Q460"];
    },

    // 加载规格数据（预留方法）
    async loadSpecs() {
      // TODO: 调用API获取规格数据
      // this.specs = await api.getSpecs();
      // 临时模拟数据用于测试
      this.specs = ["Φ12", "Φ14", "Φ16", "Φ18", "Φ20", "Φ22", "Φ25"];
    },

    // 加载所有数据源
    async loadDataSources() {
      try {
        // 并行加载所有数据源
        await Promise.all([
          this.loadStandards(),
          this.loadSteelGrades(),
          this.loadSpecs(),
        ]);
      } catch (error) {
        console.error("加载数据源失败:", error);
      }
    },
    // 查询库存
    async searchContract() {
      if (this.loading) return;

      try {
        console.log("searchForm", this.searchForm);
        console.log("currentWarehouse", this.currentWarehouse);
        this.loading = true;

        const params = {
          pageNum: 1,
          pageSize: 50,
          warehouseName: this.currentWarehouse.warehouseName,
          materialCode: this.searchForm.materialCode,
          materialName: this.searchForm.materialName,
        };

        const response = await inventoryApi.getStockReal(params);

        if (response.code === 0) {
          this.currentTable = (response.data.list || []).map((item) => ({
            ...item,
            outProdCount: item.prod_count || 0,
            outTransCount: item.trans_count || 0,
          }));

          // 搜索成功后默认切换到“当前数据”页签
          this.activeTab = "current";

          if (this.currentTable.length === 0) {
            uni.showToast({
              title: "未查询到库存数据",
              icon: "none",
            });
          }
        } else {
          uni.showToast({
            title: response.msg || "查询失败",
            icon: "error",
          });
        }
      } catch (error) {
        console.error("查询库存失败:", error);
        uni.showToast({
          title: "查询失败",
          icon: "error",
        });
      } finally {
        this.loading = false;
      }
    },

    // 重置搜索
    resetSearch() {
      this.searchForm = {
        materialCode: "",
        materialName: "",
        customerName: "",
      };
      this.currentTable = [];
      this.selectedRows = [];
    },

    // 数字验证
    validateNumber(event, item, field) {
      const value = Number(item[field]);
      if (isNaN(value) || value <= 0) {
        uni.showToast({
          title: "请输入有效的数字",
          icon: "none",
        });
        item[field] = 0;
      } else if (value > 999999) {
        uni.showToast({
          title: "数字不能超过999999",
          icon: "none",
        });
        item[field] = 999999;
      }
    },

    // 添加到出库列表
    addToOutList(item) {
      // 检查是否已经添加
      const exists = this.selectedTable.find(
        (outItem) => outItem.id === item.id
      );
      if (exists) {
        uni.showToast({
          title: "该物料已在计划列表中",
          icon: "none",
        });
        return;
      }

      // 验证数量（取新字段）
      const prodCount = Number(item.outProdCount) || 0;
      const transCount = Number(item.outTransCount) || 0;

      // 允许单项为 0，但不能同时为 0
      if (prodCount === 0 && transCount === 0) {
        uni.showToast({
          title: "计划重量和数量不能同时为 0",
          icon: "none",
        });
        return;
      }
      // 仍禁止负数
      if (prodCount < 0 || transCount < 0) {
        uni.showToast({
          title: "计划重量和数量不能为负数",
          icon: "none",
        });
        return;
      }

      // 添加到出库列表（带新字段）
      this.selectedTable.push({
        ...item,
        prodCount: Number(prodCount) || 0,
        transCount: Number(transCount) || 0,
        planDate: this.formData.currentDate, // 默认计划日期
        standNo: item.standNo || "",
        steelGradeName: item.steelGradeName || "",
        prodSpec: item.prodSpec || "",
        showError: false, // 错误状态
        // 选择器索引
        standIndex: -1,
        steelGradeIndex: -1,
        specIndex: -1,
      });

      // 清空选中状态
      this.selectedRows = [];

      // 自动切换到计划编制标签页
      this.activeTab = "selected";

      uni.showToast({
        title: "已添加到计划列表",
        icon: "success",
      });
    },

    // 从出库列表移除
    removeFromOutList(index) {
      this.selectedTable.splice(index, 1);
    },

    // 同步当前计划项数据到selectedTable
    syncCurrentPlanToTable() {
      // 如果当前有临时计划项且selectedTable为空，创建新条目
      if (this._tempPlanItem && this.selectedTable.length === 0) {
        // 验证必填字段
        if (
          !this._tempPlanItem.standNo ||
          !this._tempPlanItem.steelGradeName ||
          !this._tempPlanItem.prodSpec
        ) {
          uni.showToast({
            title: "请先选择标准、钢种和规格",
            icon: "none",
          });
          return false;
        }

        // 验证重量和数量（允许为0，但不能为空）
        if (this._tempPlanItem.ProdCount === null || this._tempPlanItem.ProdCount === undefined || this._tempPlanItem.ProdCount === '' ||
            this._tempPlanItem.TransCount === null || this._tempPlanItem.TransCount === undefined || this._tempPlanItem.TransCount === '') {
          uni.showToast({
            title: "请输入计划重量和数量",
            icon: "none",
          });
          return false;
        }

        // 添加到selectedTable
        this.selectedTable.push({
          ...this._tempPlanItem,
          id: Date.now(), // 生成唯一ID
          materialCode: `${this._tempPlanItem.standNo}-${this._tempPlanItem.steelGradeName}-${this._tempPlanItem.prodSpec}`,
          materialName: `${this._tempPlanItem.steelGradeName} ${this._tempPlanItem.prodSpec}`,
        });

        // 清空临时对象
        this._tempPlanItem = null;
        return true;
      }
      return true;
    },

    // 显示重置确认
    showResetConfirm() {
      if (this.selectedTable.length === 0) {
        this.resetForm();
        return;
      }

      uni.showModal({
        title: "确认重置",
        content: "确定要清空所有数据吗？",
        success: (res) => {
          if (res.confirm) {
            this.resetForm();
          }
        },
      });
    },

    // 重置表单
    resetForm() {
      this.formData = {
        currentDate: dateHelperApi.getCurrentDate(),
        outType: "三相",
      };
      this.searchForm = {
        materialCode: "",
        materialName: "",
        customerName: "",
      };
      this.timeFilter = "today"; // 重置时间筛选状态
      this.currentTable = [];
      this.selectedTable = [];
      this.selectedRows = [];
      this._tempPlanItem = null; // 重置临时计划项
      this.currentPlanIndex = 0; // 重置计划索引
    },

    // 提交出库单
    async submitOutOrder() {
      if (!this.canSubmit) {
        uni.showToast({
          title: "请先添加计划物料",
          icon: "none",
        });
        return;
      }

      // 验证必填项
      if (!this.formData.currentDate) {
        uni.showToast({
          title: "请选择计划日期",
          icon: "none",
        });
        return;
      }

      try {
        const submitData = this.buildSubmitData();

        // 验证数据构建是否成功
        if (!submitData) {
          return;
        }

        // 显示确认对话框
        const confirmed = await this.showSubmitConfirm(submitData);
        if (!confirmed) return;

        this.loading = true;
        const response = await lzPlanApi.submitPlan(submitData);

        if (response.code === 0) {
          await this.handleSubmitSuccess(response);
        } else {
          uni.showToast({
            title: response.msg || "提交失败",
            icon: "error",
          });
        }
      } catch (error) {
        console.error("提交计划失败:", error);
        uni.showToast({
          title: "提交计划失败",
          icon: "error",
        });
      } finally {
        this.loading = false;
      }
    },

    // 构建提交数据
    buildSubmitData() {
      const userConfig = this.$store.state.user.userConfig;
      // const targetWarehouse =
      //   this.targetWarehouseOptions[this.targetWarehouseIndex];

      // 验证所有物料的重量和数量（允许为0，但不能为空）
      for (let item of this.selectedTable) {
        if (item.prodCount === null || item.prodCount === undefined || item.prodCount === '' ||
            item.transCount === null || item.transCount === undefined || item.transCount === '') {
          uni.showToast({
            title: "请填写完整的计划量",
            icon: "none",
          });
          return null;
        }

        // 验证数字有效性
        if (
          isNaN(Number(item.outProdCount)) ||
          isNaN(Number(item.outTransCount)) ||
          Number(item.outProdCount) < 0 ||
          Number(item.outTransCount) < 0
        ) {
          uni.showToast({
            title: "计划量格式错误",
            icon: "none",
          });
          return null;
        }
      }

      return {
        id: null, // 新增时传null
        mainNo: "", // 系统自动生成
        outType: this.formData.outType,
        warehouseCode: this.currentWarehouse.warehouseId,
        warehouseName: this.currentWarehouse.warehouseName,
        ywDate: this.formData.currentDate,
        busMemo: "",
        targetWarehouseCode: targetWarehouse?.value || "",
        targetWarehouseName: targetWarehouse?.text || "",
        details: this.selectedTable.map((item) => ({
          materialCode: item.materialCode || "",
          materialName: item.materialName,
          prodCount: Number(item.outProdCount) || 0,
          countUnit: "KG",
          transCount: Number(item.outTransCount) || 0,
          tranUnit: "件",
          spec: item.spec || "",
          picNo: item.picNo || "",
          prodCompany: item.prodCompany || "",
          batchNoSerial: item.batchNoSerial || "",
          steelGradeName: item.steelGradeName || "",
          prodSpec: item.prodSpec || "",
          workShift: userConfig?.workShift || "",
          workType: userConfig?.workClass || "",
          wpEquipCode: "", // 从称重API获取（暂空）
        })),
      };
    },

    // 显示提交确认
    showSubmitConfirm(submitData) {
      return new Promise((resolve) => {
        const materialCount = submitData.details.length;
        const totalWeight = submitData.details.reduce(
          (sum, item) => sum + item.outProdCount,
          0
        );
        const totalQuantity = submitData.details.reduce(
          (sum, item) => sum + item.outTransCount,
          0
        );

        uni.showModal({
          title: "确认提交",
          content: `共${materialCount}条物料，总重量：${totalWeight}KG，总数量：${totalQuantity}件，是否确认提交？`,
          confirmText: "确认",
          cancelText: "取消",
          success: (res) => {
            resolve(res.confirm);
          },
        });
      });
    },

    // 处理提交成功
    async handleSubmitSuccess(response) {
      uni.showToast({
        title: "出库单创建成功",
        icon: "success",
        duration: 2000,
      });

      console.log("出库单创建成功:", response.data);

      // 重置表单
      this.resetForm();

      // 延迟返回上一页
      setTimeout(() => {
        uni.navigateBack();
      }, 2000);
    },
  },
};
</script>
<style scoped lang="scss">
@import "~@/pages/smart/scss/create.scss";
</style>
